/**
 * eCommerce Application Sample for J2EE Training
 * Implementation of EcomCustomerBean
 * @author Amina Chenider
 * may 2006
 */
package ecom.beans.session;

import ecom.beans.entity.Accounts;
import ecom.beans.entity.Address;
import ecom.beans.entity.Clients;
import ecom.beans.entity.Produits;
import ecom.beans.entity.Productstore;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBException;
import javax.ejb.Remote;
//import javax.ejb.SessionSynchronization;
import javax.ejb.Stateful;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateful
@Remote(EcomCustomerRemote.class)
public class EcomCustomerBean implements EcomCustomerRemote {
    @PersistenceContext
    private EntityManager em;

    private long id;
    private CartBean caddie;


    public EcomCustomerBean (){
        this.id=-1;
        this.caddie = new CartBean();
    }
    @Override
    public int getAuthentication (String email, String password) {
        try{
            Query query = em.createNamedQuery("Clients.findByLoginPwdUser");
            query.setParameter("login", email);
            query.setParameter("pwd", password);
            Clients clients = (Clients) query.getSingleResult();
            id = clients.getId();
            System.out.println("client authentifie son num  "+id);
        }
        catch(NoResultException e){
            return -1;
        }
        return 0;
    }

    @Override
    public void sendPasswordByMail(String email){
        try {
           
            String[] to = {email,null};
            String host = "smtp.gmail.com";
            String from = "minachenider@gmail.com";
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.password", "");
            props.put("mail.smtp.port", "465"); // 587 is the port number of yahoo mail
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            InternetAddress[] to_address = new InternetAddress[to.length];
            int i = 0;
            // To get the array of addresses
            while (to[i] != null) {
                to_address[i] = new InternetAddress(to[i]);
                i++;
            }
            System.out.println(Message.RecipientType.TO);
            i = 0;
            while (to_address[i] != null) {
                message.addRecipient(Message.RecipientType.TO, to_address[i]);
                i++;
            }
            message.setSubject("sending in a group");
            message.setText("Welcome to JavaMail");
            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("33333333333 ");
        } catch (AddressException ex) {
            Logger.getLogger(EcomCustomerBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(EcomCustomerBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch(Exception ex){
            //throw new Exception("");
            ex.printStackTrace();
        }
    }

    @Override
    public boolean isEmailAvailable(String email) {
        boolean res = true;
        try {
            Query q = em.createQuery("SELECT u FROM Clients WHERE email = :login");
            q.setParameter("login", email);
            q.setMaxResults(1);
            q.getSingleResult();
        } catch (NoResultException e) {
            res = false;
        }
        return res;
    }

    @Override
     public void createClients(Long id, int age, String password, String nom, String prenom,
     String email, String phone) {

        try {
            Clients clients = new Clients(id, age, password, nom, prenom, email, phone);
            em.persist(clients);
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e);
        }
    }
     
    @Override
     public Accounts getAccountByIban(String iban){
         System.out.println("OUIIIIII");
         Accounts account = null;
         Query query = null;
         try{
             //Récupère le compte correspondant à l'IBAN fourni
             System.out.println("11111");
             query = em.createNamedQuery("AccountByIban");
             System.out.println("22222");
             query.setParameter("iban", iban);
             System.out.println("333333");
             account = (Accounts) query.getSingleResult();
             System.out.println("44444");
         }
         catch (Exception ex){
             return null;
         }
         System.out.println("Account 2: "+account.getIban());
         return account;
     }
     
    /****************************************************************/
    /*                     Gestion du caddie                        */
    /****************************************************************/

    /*Cette méthode permet d'ajouter un produit au caddie*/
    @Override
    public void ajouterProductInCart(long id){
        caddie.addProduit(id);
        System.out.println("3333liste de produits: " +caddie.getProduits().size());
        return;
    }

    /*Cette méthode permet de supprimer un produit du caddie*/
    @Override
    public boolean supprimerProductInCart(long id){
        return (caddie.deleteProduit(id));
    }
    
    /*Cette méthode permet de renvoyer la liste des produits du caddie*/
    @Override
    public List<Produits> getProductInCart(){
        List<Produits> liste = new ArrayList<Produits>();
        
        List<Long> listProduits = caddie.getProduits();
        Iterator<Long> it = listProduits.iterator();
        while (it.hasNext()){
            Long cle = it.next();
            liste.add(getProductById(cle));
        }
        System.out.println("liste des prod " + liste.size());
        return liste;
    }
    /*Cette méthode permet d'acheter le caddie*/
    @Override
    public int buyCart(String email,double montant){
        //chercher le compte du client
       // if (id<0){
            Query q1 = em.createNamedQuery("Clients.findByMail");
            q1.setParameter("login", email);
            Clients client = (Clients) q1.getSingleResult();
            id = client.getId();
        //}
        Query q2 = em.createQuery("SELECT a FROM Accounts a WHERE a.clients.id = :idUser");
        q2.setParameter ("idUser", id);
        System.out.println("idddddddddddd "+id);
        List<Accounts> account = (List<Accounts>) q2.getResultList();

        //calculer le montant du caddie
        /*double montant=0;
        List prod = getProductInCart();
        Iterator it = prod.iterator();
        while (it.hasNext()){
            Produits produit = (Produits) it.next();
            montant += produit.getPrice();
        }*/
        //vérifier si le montant du caddie est inférieur à celui du compte client
        System.out.println("voici la liste de tes compte "+account.size());
        double balance = account.get(0).getBalance();
        double diff = balance - montant;
        if (diff >= 0){
            account.get(1).setBalance(diff);
            caddie.vider();
            return 0;
        }
        else{
            return -1;
        }
    }
    @Override
    public int buyCartShell(Accounts account){
        //calculer le montant du caddie
        double montant=0;
        List prod = getProductInCart();
        Iterator it = prod.iterator();
        while (it.hasNext()){
            Produits produit = (Produits) it.next();
            montant += produit.getPrice();
        }

        //vérifier si le montant du caddie est inférieur à celui du compte client
        double balance = account.getBalance();
        double diff = balance - montant;
        
        Accounts accountTemp = getAccountByIban(account.getIban());
        if (diff >= 0){
            accountTemp.setBalance(diff);
            caddie.vider();
            return 0;
        }
        else{
            return -1;
        }
    }

    @Override
    public Produits getProductById(Long id) {
        Produits produits = null;
        Query q1 = null;
        try {
            q1 = em.createNamedQuery("Produits.findById");
            q1.setParameter("id", id);
            produits = (Produits) q1.getSingleResult();
        } catch (Exception ex) {
            return null;
        }
        return produits;
    }

    @Override
    public Clients getClientsByMail(String mail){
        Clients clients = null;
        Query query = null;
        try {
            query = em.createNamedQuery("Clients.findByMail");
            query.setParameter("login", mail);
            clients = (Clients) query.getSingleResult();
        } catch (EJBException ex) {
            ex.printStackTrace();
        }
        return clients;
    }

    @Override
    public void addClientAddress(Long id, String rue, int numero, int cp, String pays) {
        Address address = null;
        try {
            System.out.println("aqui 1");
            Query q = em.createQuery("SELECT a FROM Address a WHERE a.clients.id = :id");
            q.setParameter("id", id);
            q.setMaxResults(1);
            address = (Address) q.getSingleResult();
            System.out.println("aqui 2");
            System.out.println("address != null");
            address.setPays(pays);
            address.setNumero(numero);
            address.setCp(cp);
            address.setRue(rue);
        } catch (NoResultException nre) {
            address = new Address(id, rue, numero, cp, pays);
            try {
                em.persist(address);
                Clients clients = em.find(Clients.class, id);
                address.setClients(clients);
                clients.setAddress((List<Address>) address);

            } catch (Exception e) {
                throw new EJBException(e);
            }
        } catch (Exception e) {
            throw new EJBException(e);
        }
    }
    @Override
     public void updateClientAddress(Long id, String rue, int numero, int cp, String pays) {
        this.addClientAddress(id, rue, numero, cp, pays);
    }

    @Override
    public boolean isLoginAvailable(String email) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}
